/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.utils;

import com.anhndt.audiobook.business.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;

/**
 *
 * @author Anhndt
 */
public class DBUtil {

    public static final String DB_SETTING_NAME = "db";
    public static final String DB_THEME = "db_theme";
    public static final String DB_IMAGE = "db_img";
//    public static final byte DB_RECORD_IMEI = 0;
    public static final byte DB_RECORD_USER_ID = 1;
    public static final byte DB_RECORD_LAST_ARTICLE_ID = 2;
    public static final byte DB_RECORD_DISPLAY_COUNTER = 3;
    public static final byte DB_RECORD_DISPLAY_THUMB = 4;
    public static final byte DB_RECORD_AUTO_UPDATE = 5;
    public static final byte DB_RECORD_THEMES = 6;
    public static final byte DB_RECORD_CONNECTION = 7;
    public static final byte DB_RECORD_USER_NAME = 8;
    public static final byte DB_RECORD_PASSWD = 9;
    public static final byte DB_RECORD_AUTO_LOGIN = 10;
    public static final byte DB_RECORD_REMEMBER_ACCOUNT = 11;
    public static final byte DB_RECORD_HAVE_ACCOUNT = 12;
    public static final byte DB_RECORD_THEME_ID = 13;
    public static final byte DB_RECORD_THEME_NAME = 14;
    public static final String CONNECTION_WIFI = "Wifi";
    public static final String CONNECTION_3G = "3G";
    public static final String CONNECTION_AUTO = "Auto";

    public static RecordStore open(String name) {
        try {
            return RecordStore.openRecordStore(name, true);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public static void close(RecordStore store) {
        try {
            store.closeRecordStore();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void deleteRecordStore(String recordStore) {
        try {
            RecordStore.deleteRecordStore(recordStore);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static boolean saveData(String recordStore, String id, byte[] data) {
        if (StringUtil.isNullOrEmpty(id)) {
            return false;
        }
        RecordStore rms = null;
        try {
            rms = open(recordStore);
            byte[] realByte;
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(bout);
            dout.writeUTF(id);
            dout.writeInt(data.length);
            dout.write(data);
            realByte = bout.toByteArray();

            rms.addRecord(realByte, 0, realByte.length);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(rms);
        }
        return false;
    }

    public static byte[] loadData(String recordStore, String id) {
        if (StringUtil.isNullOrEmpty(id)) {
            return null;
        }
        RecordStore rms = null;
        byte[] data = null;
        try {
            rms = open(recordStore);
            RecordEnumeration re = rms.enumerateRecords(null, null, true);
            byte[] rec;
            while (re.hasNextElement()) {
                rec = re.nextRecord();
                ByteArrayInputStream bin = new ByteArrayInputStream(rec);
                DataInputStream din = new DataInputStream(bin);
                String dataID = din.readUTF();
                if (!dataID.equals(id)) {
                    continue;
                }
                int length = din.readInt();
                data = new byte[length];
                //  Serialize the image raw data
                for (int ite = 0; ite < length; ite++) {
                    data[ite] = din.readByte();
                }
                din.close();
                bin.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(rms);
        }
        return data;
    }

    //Setting
    public static void loadSetting() {
        Util.themeID = getValue(DB_RECORD_THEME_ID, "0");
        Util.lastArticleID = getValue(DB_RECORD_LAST_ARTICLE_ID);
        String displayCounter = getValue(DB_RECORD_DISPLAY_COUNTER, "" + Util.displayCounter);
        String displayThumb = getValue(DB_RECORD_DISPLAY_THUMB, Resource.TXT_YES);
        String autoUpdate = getValue(DB_RECORD_AUTO_UPDATE, Resource.TXT_YES);
        Util.connection = getValue(DB_RECORD_CONNECTION, CONNECTION_AUTO);
        Util.displayThumb = displayThumb.equals(Resource.TXT_YES) ? true : false;
        try {
            Util.displayCounter = Integer.parseInt(displayCounter);
        } catch (Exception e) {
        }
    }

    public static Integer getRecordID(byte key) {
        long curTime = System.currentTimeMillis();
        RecordStore rms = null;
        try {
            rms = open(DB_SETTING_NAME);
            RecordEnumeration re = rms.enumerateRecords(null, null, true);
            byte[] rec;
            int recID;
            while (re.hasNextElement()) {
                recID = re.nextRecordId();
                rec = rms.getRecord(recID);

                ByteArrayInputStream bin = new ByteArrayInputStream(rec);
                DataInputStream din = new DataInputStream(bin);
                byte b = din.readByte();
                if (b == key) {
                    return new Integer(recID);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(rms);
        }
        long time = System.currentTimeMillis() - curTime;
//        System.out.println("[DBUtil getRecordID : key = " + key + "]    " + time);
        return null;
    }

    public static String getValue(byte key) {
        return getValue(key, null);
    }

    public static String getValue(byte key, String defaultValue) {
        String value = null;
        Integer recID = getRecordID(key);

        if (recID != null) {
            long curTime = System.currentTimeMillis();
            RecordStore rms = open(DB_SETTING_NAME);
            try {
                byte[] rec = rms.getRecord(recID.intValue());
                ByteArrayInputStream bin = new ByteArrayInputStream(rec);
                DataInputStream din = new DataInputStream(bin);
                byte b = din.readByte();
                value = din.readUTF();
                din.close();
                bin.close();
                close(rms);
                long time = System.currentTimeMillis() - curTime;
//                System.out.println("[DBUtil getValue : key = " + key + "]    " + time);
            } catch (Exception e) {
            }
        } else {
            //put default value into RMS
            changeValue(key, defaultValue);
        }

        return value != null ? value : defaultValue;
    }

    public static void changeValue(byte key, String value) {
        delete(key);
        putValue(key, value);
    }

    public static void delete(byte key) {
        try {
            RecordStore rms = open(DB_SETTING_NAME);
            Integer recID = getRecordID(key);
            if (recID != null) {
                rms.deleteRecord(recID.intValue());
            }
            close(rms);
        } catch (Exception e) {
        }
    }

    public static void putValue(byte key, String value) {
        if (value == null) {
            return;
        }
        long curTime = System.currentTimeMillis();
        try {
            RecordStore rms = open(DB_SETTING_NAME);
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            DataOutputStream dout = new DataOutputStream(bout);
            dout.writeByte(key);
            dout.writeUTF(value);

            byte[] realByte = bout.toByteArray();
            rms.addRecord(realByte, 0, realByte.length);
            dout.close();
            bout.close();
            close(rms);
            long time = System.currentTimeMillis() - curTime;
        } catch (Exception e) {
        }
    }
}
